{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                \n",
    "                for n in range(num_layers):\n",
    "                    (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                        cell_fw = cells(size_layer // 2),\n",
    "                        cell_bw = cells(size_layer // 2),\n",
    "                        inputs = encoder_embedded,\n",
    "                        sequence_length = X_seq_len,\n",
    "                        dtype = tf.float32,\n",
    "                        scope = 'bidirectional_rnn_%d'%(n))\n",
    "                    encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "                \n",
    "                bi_state = tf.concat((state_fw,state_bw), -1)\n",
    "                last_state = tuple([bi_state] * num_layers)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = last_state,\n",
    "                                               dtype = tf.float32)\n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-981e29d6c0ce>:11: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-981e29d6c0ce>:36: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-7-981e29d6c0ce>:43: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-981e29d6c0ce>:48: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 13938,  8345,  8345, 14186, 26764, 25757, 15817, 29790,\n",
       "          29269,   730, 22327, 22327, 22327,  4484,  5805,  5805,  5805,\n",
       "            781,   781,  6936, 14832, 14832, 24701, 24701, 24701,  5844,\n",
       "          20126, 20126, 20126, 20126, 20126, 22872, 22872, 20343, 20343,\n",
       "          20343]],\n",
       " \n",
       "        [[    1,  4154, 25042, 10774,  6937,  6937,  6937,  7613, 10462,\n",
       "          10462, 29060, 26384, 26384, 26384, 26384, 26384, 29351, 29351,\n",
       "             54,    54, 31323,   554,  7297,  7297, 27100, 27100, 27100,\n",
       "            600,   600, 23285, 23285, 23285,  6134,  6134, 31160, 31160,\n",
       "          31160]],\n",
       " \n",
       "        [[    1, 21744, 21744, 21744,  4760,  4760,  4760, 25229, 30517,\n",
       "          30517, 25229, 20311,  7714,  7714,  7714,  8515,  8515, 29331,\n",
       "          29331, 26839, 26839, 26839, 26839, 26839, 11992, 11992,   937,\n",
       "            937,   937, 12250, 12250, 12250, 12250, 26158, 25340, 25340,\n",
       "           8487]],\n",
       " \n",
       "        [[    1,  9927,  9927, 19749, 10989, 10989, 10989, 20886, 20886,\n",
       "          20886, 20886, 20886, 24308,  2567,  5809,  5809,  4463,  4463,\n",
       "           4463, 17614,  4463,  3676,  5078,  5078,  5078, 15235, 15235,\n",
       "           8239,  8239, 12600, 12600, 12600, 12600, 22153, 22153, 22153,\n",
       "          22153]],\n",
       " \n",
       "        [[    1, 25542,  1377,  1377, 20631, 21967, 21967, 11844, 16455,\n",
       "          16455, 16274, 16274, 13782, 13782,  9593,  9593,  9593,  9593,\n",
       "          20914,  5082, 14145, 14145,   257, 30851, 30851, 30851, 30851,\n",
       "          13910, 29007, 29007,  6538,  6538,  6538,  6538,  9754,  9754,\n",
       "          19715]],\n",
       " \n",
       "        [[    1,  4719, 17239, 17239, 28455, 29520, 23543, 23543, 29841,\n",
       "          29841, 16992, 10554, 10554,  4688, 17211, 20625, 20625, 20625,\n",
       "          20625, 11645, 11645,  3506, 30731, 30731, 30731, 11570, 13081,\n",
       "          23588, 23588,  8320, 23588, 25592, 25592, 31456, 16823, 16823,\n",
       "           8027]],\n",
       " \n",
       "        [[    1, 12687, 12687, 10287,  1688, 27283, 27283,  4668,  4668,\n",
       "          14642, 25985, 11446, 11446, 11446, 11446,  1725, 29573, 29573,\n",
       "          29573, 29573, 29573, 23551, 21031, 23551, 23551, 23551, 12781,\n",
       "          12781, 25342, 29499, 29499, 14269, 14269, 14269, 20349, 20349,\n",
       "          20349]],\n",
       " \n",
       "        [[    1, 24167, 27050, 20829, 20829, 17044, 17044,  5993, 28321,\n",
       "          28321, 28321, 28321, 12024, 12024, 12024, 30162, 30162, 30162,\n",
       "          30162, 22796, 22796, 22796, 13782, 13782, 13782, 13782,  1226,\n",
       "          28739, 28739, 28739, 28739, 29374, 28242, 28242, 17099, 21210,\n",
       "          25472]],\n",
       " \n",
       "        [[    1,   388, 12831, 12831, 12831, 26975, 26975,  2840, 20571,\n",
       "           2134,  2134,  3335, 10751, 10751, 10751, 24942, 24942, 10919,\n",
       "          10919, 10919, 10021, 10021, 10021, 10021, 10021,  3329, 31909,\n",
       "          11306,  7614,  7614, 14543, 14543, 14543, 14543,  9044,  9044,\n",
       "           9561]],\n",
       " \n",
       "        [[    1,  7345,  7345,  7345, 17415, 24456, 24456, 24456,  3291,\n",
       "           2454,  2454,  3127, 23568, 23568,  6213,  6213, 29033, 23173,\n",
       "          23173, 15292, 15292, 15292, 24058, 18943, 19299,  8014, 15661,\n",
       "           9308,  9308,  9308, 27761, 27761, 16540, 30025, 30025,  7150,\n",
       "           7150]]], dtype=int32), 10.373073, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:14<00:00,  2.54it/s, accuracy=0.118, cost=6.63]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.94it/s, accuracy=0.145, cost=6.39]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.219291, training avg acc 0.100421\n",
      "epoch 1, testing avg loss 6.534189, testing avg acc 0.131997\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:18<00:00,  2.53it/s, accuracy=0.138, cost=5.74]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.96it/s, accuracy=0.14, cost=6]    \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 6.174939, training avg acc 0.143287\n",
      "epoch 2, testing avg loss 6.044876, testing avg acc 0.146936\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:14<00:00,  2.54it/s, accuracy=0.162, cost=4.98]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.04it/s, accuracy=0.134, cost=5.84]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.602458, training avg acc 0.161607\n",
      "epoch 3, testing avg loss 5.876627, testing avg acc 0.149628\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:38<00:00,  2.45it/s, accuracy=0.195, cost=4.41]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.90it/s, accuracy=0.134, cost=5.93]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.182189, training avg acc 0.178061\n",
      "epoch 4, testing avg loss 5.842999, testing avg acc 0.149361\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:12<00:00,  2.55it/s, accuracy=0.234, cost=4.03]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.04it/s, accuracy=0.129, cost=5.9] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.861722, training avg acc 0.193830\n",
      "epoch 5, testing avg loss 5.865521, testing avg acc 0.148210\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:34<00:00,  2.46it/s, accuracy=0.29, cost=3.67] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.08it/s, accuracy=0.145, cost=5.89]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.623650, training avg acc 0.208286\n",
      "epoch 6, testing avg loss 5.952721, testing avg acc 0.147296\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:13<00:00,  2.55it/s, accuracy=0.332, cost=3.4] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.02it/s, accuracy=0.145, cost=5.99]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.431728, training avg acc 0.223065\n",
      "epoch 7, testing avg loss 6.022382, testing avg acc 0.145286\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:31<00:00,  2.48it/s, accuracy=0.349, cost=3.22]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.34it/s, accuracy=0.129, cost=6.06]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.283268, training avg acc 0.236092\n",
      "epoch 8, testing avg loss 6.122346, testing avg acc 0.142983\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:01<00:00,  2.60it/s, accuracy=0.368, cost=3.06]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.22it/s, accuracy=0.124, cost=6.09]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.168940, training avg acc 0.246226\n",
      "epoch 9, testing avg loss 6.227079, testing avg acc 0.141388\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:01<00:00,  2.60it/s, accuracy=0.379, cost=3.06]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.27it/s, accuracy=0.151, cost=6.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.062998, training avg acc 0.256642\n",
      "epoch 10, testing avg loss 6.310319, testing avg acc 0.138835\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:02<00:00,  2.59it/s, accuracy=0.407, cost=2.88]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.18it/s, accuracy=0.129, cost=6.37]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 3.965103, training avg acc 0.267382\n",
      "epoch 11, testing avg loss 6.414697, testing avg acc 0.135819\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:01<00:00,  2.60it/s, accuracy=0.415, cost=2.77]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.14it/s, accuracy=0.124, cost=6.52]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 3.883876, training avg acc 0.276383\n",
      "epoch 12, testing avg loss 6.499417, testing avg acc 0.134299\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:01<00:00,  2.60it/s, accuracy=0.406, cost=2.75]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.12it/s, accuracy=0.167, cost=6.39]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.815408, training avg acc 0.284068\n",
      "epoch 13, testing avg loss 6.557990, testing avg acc 0.135861\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:09<00:00,  2.56it/s, accuracy=0.44, cost=2.69] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.06it/s, accuracy=0.134, cost=6.4] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.753836, training avg acc 0.291289\n",
      "epoch 14, testing avg loss 6.646185, testing avg acc 0.132901\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:11<00:00,  2.56it/s, accuracy=0.436, cost=2.64]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.00it/s, accuracy=0.134, cost=6.45]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.696947, training avg acc 0.297804\n",
      "epoch 15, testing avg loss 6.744807, testing avg acc 0.130500\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:23<00:00,  2.51it/s, accuracy=0.464, cost=2.55]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.93it/s, accuracy=0.14, cost=6.56] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.646482, training avg acc 0.304351\n",
      "epoch 16, testing avg loss 6.785120, testing avg acc 0.131019\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:36<00:00,  2.45it/s, accuracy=0.461, cost=2.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.86it/s, accuracy=0.134, cost=6.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.599636, training avg acc 0.310070\n",
      "epoch 17, testing avg loss 6.836185, testing avg acc 0.129763\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:38<00:00,  2.45it/s, accuracy=0.457, cost=2.49]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.90it/s, accuracy=0.134, cost=6.72]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.557307, training avg acc 0.315471\n",
      "epoch 18, testing avg loss 6.910698, testing avg acc 0.129052\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:41<00:00,  2.44it/s, accuracy=0.483, cost=2.36]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.79it/s, accuracy=0.124, cost=6.74]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.516622, training avg acc 0.320655\n",
      "epoch 19, testing avg loss 6.978038, testing avg acc 0.128969\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:42<00:00,  2.43it/s, accuracy=0.483, cost=2.41]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.83it/s, accuracy=0.134, cost=6.88]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.481431, training avg acc 0.325354\n",
      "epoch 20, testing avg loss 7.039040, testing avg acc 0.129329\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [03:58<00:00,  5.95s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0095551545"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
